/**
 * 
 */
package com.ffcs.crmd.tsp.server.netty.processor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ffcs.crmd.tsp.api.dto.client.TspJobDetailRetry;
import com.ffcs.crmd.tsp.api.dto.netty.RemotingCommand;
import com.ffcs.crmd.tsp.api.dto.page.PageInfo;
import com.ffcs.crmd.tsp.api.dto.page.RetVo;
import com.ffcs.crmd.tsp.api.dto.task.TspJobInstance;
import com.ffcs.crmd.tsp.api.netty.INettyProcessor;
import com.ffcs.crmd.tsp.common.constant.LoggerName;
import com.ffcs.crmd.tsp.common.netty.ResponseCode;
import com.ffcs.crmd.tsp.core.util.XmlUtil;
import com.ffcs.crmd.tsp.server.application.ApplicationManagerHolder;
import com.ffcs.crmd.tsp.server.core.DataBaseHandler;
import com.ffcs.crmd.tsp.server.core.RemotingHandler;
import com.ffcs.crmd.tsp.server.jdbc.entity.Job;
import com.ffcs.crmd.tsp.server.jdbc.entity.JobDetail;
import com.ffcs.crmd.tsp.server.jdbc.entity.JobGroup;
import com.ffcs.crmd.tsp.server.job.info.JobDetailShell;
import com.ffcs.crmd.tsp.server.manager.JobProcessManager;

import io.netty.channel.ChannelHandlerContext;

/**
 * 功能说明:
 *
 * @author ZHONGFUHUA
 * 
 * @since 
 *
 */
public class QueryJobDetailRetryProcessor implements INettyProcessor {
    /**
     * 日志
     */
    private final static Logger LOG               = LoggerFactory.getLogger(LoggerName.RemotingLoggerName);
    
    /**
     * 任务数据库服务
     */
    private DataBaseHandler     dataBaseHandler;
    
    /**
     * 任务端管理器
     */
    private JobProcessManager   jobProcessManager = ApplicationManagerHolder.getBean("jobProcessManager", JobProcessManager.class);
    
    /**
     * 功能说明:
     * 
     * @param remotingController
     */
    public QueryJobDetailRetryProcessor(RemotingHandler remotingController, DataBaseHandler dataBaseHandler) {
        this.dataBaseHandler = dataBaseHandler;
    }
    
    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) {
        RemotingCommand response = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS);
        String requestXml = new String(request.getBody());
        try {
            LOG.info("SERVER-NETTY: one request to query job detail retry is received that body=[{}]", requestXml);
            TspJobDetailRetry tspJobDetailRetryVO = (TspJobDetailRetry) XmlUtil.fromXml(requestXml, TspJobDetailRetry.class);
            List<Job> jobList = new ArrayList<Job>();
            if (StringUtils.isNoneBlank(tspJobDetailRetryVO.getJobGroupName())) {
                JobGroup jobGroupParam = new JobGroup();
                jobGroupParam.setName(tspJobDetailRetryVO.getJobGroupName());
                jobGroupParam.setClusterName(tspJobDetailRetryVO.getClusterName());
                JobGroup jobGroup = dataBaseHandler.getServiceSupport().getJobGroup(jobGroupParam);
                
                if(jobGroup != null){
                    Job jobParam = new Job();
                    jobParam.setJobGroupId(jobGroup.getId());
                    jobList.addAll(dataBaseHandler.getServiceSupport().queryJob(jobParam));
                }
            } else if (StringUtils.isNoneBlank(tspJobDetailRetryVO.getJobName())) {
                Job jobParam = new Job();
                jobParam.setName(tspJobDetailRetryVO.getJobName());
                jobParam.setClusterName(tspJobDetailRetryVO.getClusterName());
                jobList.add(dataBaseHandler.getServiceSupport().getJob(jobParam));
            } else if (StringUtils.isNoneBlank(tspJobDetailRetryVO.getJobDetailName())) {
                JobDetail jobDetailParam = new JobDetail();
                jobDetailParam.setName(tspJobDetailRetryVO.getJobDetailName());
                jobDetailParam.setClusterName(tspJobDetailRetryVO.getClusterName());
                JobDetail jobDetail = dataBaseHandler.getServiceSupport().getJobDetail(jobDetailParam);
                
                Job jobParam = new Job();
                jobParam.setId(jobDetail.getJobId());
                jobList.add(dataBaseHandler.getServiceSupport().getJob(jobParam));
            }else{
                Job jobParam = new Job();
                jobList.addAll(dataBaseHandler.getServiceSupport().queryJob(jobParam));
            }
            
            List<TspJobDetailRetry> tspJobDetailRetryVOList = new ArrayList<TspJobDetailRetry>();
            if(CollectionUtils.isNotEmpty(jobList)){
                for (Job job : jobList) {
                    List<JobDetailShell> jobDetailWaitingList = jobProcessManager.getJobDetailRetry(job.getName());
                    if (CollectionUtils.isNotEmpty(jobDetailWaitingList)) {
                        for (JobDetailShell jobDetailShell : jobDetailWaitingList) {
                            TspJobInstance tspJobInstance = jobDetailShell.getContext().getTspJobInstance();
                            if (StringUtils.isNoneBlank(tspJobDetailRetryVO.getJobDetailName())
                                && !tspJobDetailRetryVO.getJobDetailName().equals(tspJobInstance.getName())) {
                                continue;
                            }
                            
                            if(StringUtils.isNoneBlank(tspJobDetailRetryVO.getId()) && 
                                !jobDetailShell.getId().equals(tspJobDetailRetryVO.getId())){
                                continue;
                            }
                            
                            TspJobDetailRetry tspJobDetailRetry = new TspJobDetailRetry();
                            tspJobDetailRetry.setId(jobDetailShell.getId());
                            tspJobDetailRetry.setJobDetailName(tspJobInstance.getName());
                            tspJobDetailRetry.setJobName(tspJobInstance.getJobName());
                            tspJobDetailRetry.setStatus(jobDetailShell.getStatus());
                            tspJobDetailRetry.setClusterName(jobDetailShell.getClusterName());
                            tspJobDetailRetry.setInstanceId(jobDetailShell.getInstanceId());
                            tspJobDetailRetry.setFireTime(jobDetailShell.getFireTime());
                            tspJobDetailRetry.setRefireCount(jobDetailShell.getContext().getRefireCount());
                            tspJobDetailRetry.setDescription(jobDetailShell.getContext().getTspJobInstance().getDescription());
                            tspJobDetailRetryVOList.add(tspJobDetailRetry);
                        }
                    }
                }
            }
            
            Collections.sort(tspJobDetailRetryVOList, new Comparator<TspJobDetailRetry>() {
                @Override
                public int compare(TspJobDetailRetry o1, TspJobDetailRetry o2) {
                    return o1.getId().compareTo(o2.getId());
                }
            });
            
            RetVo<TspJobDetailRetry> retVO = new RetVo<TspJobDetailRetry>();
            if (tspJobDetailRetryVO.getPageNumber() != null && tspJobDetailRetryVO.getPageSize()!= null 
                && tspJobDetailRetryVO.getPageNumber() > 0 && tspJobDetailRetryVO.getPageSize() > 0) {
                int pageNumber = tspJobDetailRetryVO.getPageNumber();
                int pageSize = tspJobDetailRetryVO.getPageSize();
                int totalCounts = tspJobDetailRetryVOList.size();
                int first = PageInfo.getPageBeginSize(pageSize, pageNumber);
                int end = PageInfo.getPageEndSize(first, pageSize, totalCounts);
                
                List<TspJobDetailRetry> ntspJobDetailWaitingVOList = new ArrayList<TspJobDetailRetry>();
                ntspJobDetailWaitingVOList.addAll(tspJobDetailRetryVOList.subList(first, end));
                PageInfo<TspJobDetailRetry> pageInfo = new PageInfo<TspJobDetailRetry>(ntspJobDetailWaitingVOList);
                pageInfo.calcAndJudge(pageSize, pageNumber, totalCounts, ntspJobDetailWaitingVOList);
                retVO.setPageInfo(pageInfo);
            } else {
                retVO.setDataList(tspJobDetailRetryVOList);
            }
            response.setBody(XmlUtil.toXml(retVO).getBytes());
        } catch (Exception e) {
            LOG.error("SERVER-NETTY: query job detail retry[{}] exception:", requestXml, e);
            String responseBody = String.format("query job detail retry exception:%s", e.getMessage());
            response.setCode(ResponseCode.FAIL);
            response.setBody(responseBody.getBytes());
        }
        return response;
    }
}
